package com.qire.antsdeeplink;

import android.app.Application;
import android.content.Intent;
import android.content.pm.PackageManager;

import com.qire.antscore.common.AssertUtils;
import com.qire.antsdeeplink.utils.ClassUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

public class AntsDeepLink {

    public static final AntsDeepLink DISPATCHER = new AntsDeepLink();

    private List<DeepLinkDispatchRegistry> dispatchRegistryList = new ArrayList<>();

    private volatile boolean needInit = true;

    private AntsDeepLink() {
    }

    public synchronized void init(Application application) {
        if(needInit) {
            needInit = false;
            try {
                loadInfo(application);
            } catch (PackageManager.NameNotFoundException | InterruptedException | ClassNotFoundException e) {
                e.printStackTrace();
            }
            return;
        }
    }

    private void loadInfo(Application application) throws PackageManager.NameNotFoundException, InterruptedException, ClassNotFoundException {
        final String PACKAGE_OF_GENERATE_FILE = "com.qire.antsdeeplink.registry";
        final String CLASS_NAME_PREFIX = "DispatchRegistry";
        // 路由派发映射表类名前缀 com.qire.antsdeeplink.registry.DispatchRegistry
        String dispatchRegistryNamePrefix = PACKAGE_OF_GENERATE_FILE + "." + CLASS_NAME_PREFIX;

        // 获得所有 apt 生成的所有路由派发映射表
        Set<String> routerMap = ClassUtils.getClassNamesByPackageName(application, PACKAGE_OF_GENERATE_FILE);
        for (String className : routerMap) {
            if (className.startsWith(dispatchRegistryNamePrefix)) {
                Class<DeepLinkDispatchRegistry> cls = (Class<DeepLinkDispatchRegistry>) Class.forName(className);
                addDispatchRegistry(ClassUtils.newInstance(cls));
            }
        }
    }

    public void addDispatchRegistry(DeepLinkDispatchRegistry dispatchRegistry) {
        if(!dispatchRegistryList.contains(dispatchRegistry)) {
            dispatchRegistryList.add(dispatchRegistry);
        }
    }


    public void receiveFrom(Intent deepLinkIntent) {
        if(AssertUtils.nonNull(deepLinkIntent)) {
            DeepLinkUri deepLinkUri = DeepLinkUri.parseFrom(deepLinkIntent);
            new DeepLinkDispatcher().dispatchFrom(deepLinkUri, dispatchRegistryList);
        }
    }


}
